package com.itheima.admin.controller;

import com.itheima.admin.dto.ChannelPageRequestDto;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.admin.service.AdChannelService;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @program: itheima-leadnews
 * @description: 控制层
 * @author: pw
 * @create: 2022-08-09 23:25
 **/
@RestController
@RequestMapping("/channel")
@Api(tags = "频道管理")
public class AdChannelController {

    @Autowired
    private AdChannelService channelService;

    //传输的是两个参数
    @PostMapping("/list")
    @ApiOperation(value = "频道分页查询")
    public PageResultVo<AdChannel> list(@RequestBody ChannelPageRequestDto pageRequestDto) {
        PageResultVo<AdChannel> pageResultVo = channelService.pageList(pageRequestDto);
        return pageResultVo;
    }

    // 增加一个频道
    @PostMapping("/save")
    @ApiOperation(value = "频道增加")
//    validated开启与表当中数据的校验
    public ResultVo save(@Validated @RequestBody AdChannel adChannel) {
//一般来说进行非空判断  但是这个对象一定不为空
        adChannel.setIsDefault(false);
        adChannel.setCreatedTime(new Date());
        channelService.save(adChannel);
        return ResultVo.ok("操作成功");
    }

    //    根据id查询  先查询然后更新
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询频道")
    public ResultVo findById(@PathVariable int id) {
//       返回这一份数据
        return ResultVo.ok(channelService.getById(id));
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新频道")
//    可以在这里进行校验
    public ResultVo update(@RequestBody AdChannel adChannel) {
        if (adChannel == null) {
            ResultVo.bizError("更新失败");
        }
        channelService.updateById(adChannel);
        return ResultVo.ok("更新成功");
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "删除频道")
    public ResultVo delete(@PathVariable int id) {

        if (channelService.removeById(id)) {
            return ResultVo.ok("删除成功");
        }
        return ResultVo.ok("删除失败");


    }
}
